const Router = require("@koa/router");
const jwt = require("jsonwebtoken");
const bcrypt = require("bcrypt");
const router = new Router();
const multer = require("multer");
const path = require("path");
const uuid = require('uuid');
// 设置图片存储目录和文件名
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, "uploads/");
  },
  filename: function (req, file, cb) {
    // 生成唯一标识符作为文件名
    const filename = uuid.v4();
    const extension = path.extname(file.originalname);
    console.log(filename+extension);
    cb(null, filename+extension);
  },
});

// 设置上传文件过滤器，这里仅允许上传图片文件
const fileFilter = function (req, file, cb) {
  const allowedTypes = [
    "image/jpeg",
    "image/png",
    "image/webp",
    "image/jpeg",
    "image/jfif",
  ];
  if (allowedTypes.includes(file.mimetype)) {
    cb(null, true);
  } else {
    cb(null, false);
  }
};

// 配置 multer 中间件
const upload = multer({
  storage: storage,
  fileFilter: fileFilter,
});

// 验证用户身份的中间件
const authenticateUser = async (ctx, next) => {
  const token = ctx.headers.authorization;

  if (!token) {
    ctx.status = 401;
    ctx.body = {error: "未提供身份验证令牌。"};
    return;
  }

  // 解码 base64 编码的 token
  const decodedToken = Buffer.from(token, "base64").toString("utf-8");

  jwt.verify(decodedToken, "token", (err, decoded) => {
    if (err) {
      ctx.status = 401;
      ctx.body = {error: "无效的身份验证令牌。"};
      return;
    }

    ctx.state.userId = decoded.userId;
  });

  await next(); // 使用 await next() 调用
};

// 图片上传接口，需要验证 token
router.post("/imageupload", async (ctx, next) => {
  try {
    await new Promise((resolve, reject) => {
      upload.single("file")(ctx.req, ctx.res, (err) => {
        if (err) {
          reject(err);
        } else {
          resolve();
        }
      });
    });

    // 获取上传的文件信息
    const file = ctx.req.file;

    if (!file) {
      ctx.status = 400; // Bad request
      ctx.body = {
        success: false,
        message: "未上传文件",
      };
      return;
    }

    // 构造图片链接地址
    ctx.body = {
      success: true,
      message: "图片上传成功",
      imageUrl: `http://localhost:12121/${file.filename}`, // 设置图片链接地址
    };
  } catch (err) {
    ctx.status = 500; // 服务器内部错误
    ctx.body = {
      success: false,
      message: "Internal Server Error" + err,
    };
  }
});

module.exports = router;
